package com.hisicom.scqxspxcjc.base.filter;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.hisicom.scqxspxcjc.base.bean.Result;
import com.hisicom.scqxspxcjc.base.enums.ResultEnum;
import com.hisicom.scqxspxcjc.base.tool.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 描述: JwtToken 过滤器
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
@Slf4j
@Component
public class LoginFilter implements Filter {
    private String[] noFilterUrls = new String[]{"/sceneCheckApi/","sceneCheck/systemCheck/file/save", "/sceneCheck/login", "sceneCheck/systemCheck/file/getFileById"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        // 从过滤器配置中获取initParams参数
//        String noFilterUrl = filterConfig.getInitParameter("noFilterUrl");
//        // 将排除的URL放入成员变量noFilterUrls中
//        if (StrUtil.isNotBlank(noFilterUrl)) {
//            noFilterUrls = new ArrayList<>(Arrays.asList(noFilterUrl.split(",")));
//        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.setHeader("Content-Type", "application/json;charset=UTF-8");
        resp.setHeader("Cache-Control", "no-cache");
        // 若请求中包含noFilterUrls中的片段则直接跳过过滤器进入下一步请求中
        String url = ((HttpServletRequest) servletRequest).getRequestURI();
        Boolean flag = false;
        if (!ObjectUtil.isEmpty(noFilterUrls)) {
            for (String noFilterUrl : noFilterUrls) {
                if (url.indexOf(noFilterUrl) > -1) {
                    flag = true;
                    break;
                }
            }
        }
        if (!flag) {
            try {
                Enumeration<String> eEnumeration = ((HttpServletRequest) servletRequest).getHeaders("Authorization");
                String token = eEnumeration.nextElement();
                //验证密码
                Result result = JwtTokenUtil.appVerifyUser(token, resp);
                if (!result.getSuccess()) {
                    resp.getWriter().write(JSONObject.toJSONString(result));
                    return;
                }
            } catch (Exception e) {
                resp.getWriter().write(JSONObject.toJSONString(Result.error(ResultEnum.ERROR401)));
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}